/**
 * UI交互相关功能 Composable
 * 包含界面交互、状态管理等功能
 */
import { ref, computed, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'

export function useUIInteractions() {
  const router = useRouter()
  const route = useRoute()

  // 响应式数据
  const editName = ref(false)
  const uavLinesInfoList = ref([
    ['航线总长', '0.00 m'],
    ['巡检类型', '逐点巡检'],
    ['往返长度', '0.00 m'],
    ['用户航点', '0 个'],
    ['规划航点', '0 个'],
    ['预计时间', '0 s'],
  ])

  // 选项配置
  const modeOption = ref({
    '0': '逐点记录',
    '1': '区域记录',
    '2': '斜面记录',
    '3': '沿线记录',
    '4': '立体记录',
  })

  const modeNameOption = ref({
    '0': '逐点巡检',
    '1': '区域巡检',
    '2': '斜面巡检',
    '3': '沿线巡检',
    '4': '立体巡检',
  })

  const gimbalModeOptions = ref([{
    value: 0,
    label: "自动计算",
  }, {
    value: 1,
    label: "手动设置",
  }])

  const flightPathModeOptions = ref([{
    value: 1,
    label: '直线飞行（过点且到点停）'
  }, {
    value: 2,
    label: '协调转弯（提前转弯不过点）'
  }, {
    value: 3,
    label: '曲线飞行（到点停）'
  }, {
    value: 4,
    label: '曲线飞行（不到点停）'
  }])

  const headingModeOptions = ref([{
    value: 0,
    label: '自动'
  }, {
    value: 1,
    label: '锁定'
  }, {
    value: 2,
    label: '遥控器控制'
  }, {
    value: 3,
    label: '云台依照航点方向旋转'
  }, {
    value: 4,
    label: '朝向兴趣点'
  }, {
    value: 5,
    label: '飞机和云台的偏航同时旋转'
  }])

  const actionOptions = ref([
    {
      value: 0,
      label: "拍照",
    },
    {
      value: 1,
      label: "开始录像",
    },
    {
      value: 2,
      label: "结束录像",
    },
    {
      value: 6,
      label: "转动云台",
    },
    {
      value: 40,
      label:"地面点设置",
    },
    {
      value:7,
      label:"变焦",
    },
    {
      value:8,
      label:"等时连续拍照开始",
    },
    {
      value:9,
      label:"等距连续拍照开始",
    },
    {
      value:10,
      label:"连续拍照结束",
    },
    {
      value:11,
      label:"喊话器",
    },
    {
      value:12,
      label:"探照灯开启",
    },
    {
      value:13,
      label:"探照灯关闭",
    }
  ])

  // 计算属性
  const currentMode = computed(() => {
    let modeString = '逐点巡检'
    switch (route.query.mode) {
      case '0':
        modeString = '逐点巡检'
        break
      case '1':
        modeString = '区域巡检'
        break
      case '2':
        modeString = '斜面巡检'
        break
      case '3':
        modeString = '沿线巡检'
        break
      case '4':
        modeString = '立体巡检'
        break
      default:
        modeString = '逐点巡检'
        break
    }
    return modeString
  })

  // 方法

  /**
   * 输入框失去焦点重名检测
   */
  const duplicate_check = async () => {
    editName.value = false
  }

  /**
   * 点击编辑名字
   * @param {Object} reNameRef - 重命名输入框的ref
   */
  const reName = async (reNameRef) => {
    if (editName.value) {
      editName.value = false
    } else {
      editName.value = true
      await nextTick()
      reNameRef.value?.focus()
    }
  }

  /**
   * 返回航线任务总列表
   */
  const backUavTask = () => {
    ElMessageBox.confirm('您操作了数据, 是否已经保存?', '提示', {
      confirmButtonText: '已经保存，确定返回',
      cancelButtonText: '未保存，取消返回',
      type: 'warning'
    }).then(() => {
      router.push({
        path: "/uavtask",
      })
    })
  }

  /**
   * 清空所有cesium数据
   * @param {Object} bus - 事件总线实例
   */
  const clear = (bus) => {
    if (bus) {
      bus.emit('clearReadingRoute')
    }
  }

  /**
   * 更新空地连线
   * @param {Object} uavPosition - 无人机位置
   * @param {Object} currentRecord - 当前记录
   * @param {string} ugLineLayerName - 连线图层名称
   */
  const updateUGConnect = (uavPosition, currentRecord, ugLineLayerName) => {
    console.log('更新连线', currentRecord.point_actions)
    const objId = currentRecord.uavId
    clearLayersEntity(ugLineLayerName, objId)
    
    if (currentRecord.point_actions.length == 0) return
    
    const item = currentRecord.point_actions[0]
    let positions = []
    positions.push(uavPosition)
    const groundPosition = Cesium.Cartesian3.fromDegrees(
      item.groundPosition.longitude, 
      item.groundPosition.latitude, 
      item.groundPosition.altitude
    )
    positions.push(groundPosition)
    showPolyline(objId, positions, ugLineLayerName)
  }

  /**
   * 清空指定图层的实体
   * @param {string} layerId - 图层ID
   * @param {string} objId - 对象ID
   */
  const clearLayersEntity = (layerId, objId) => {
    let entityList = window.viewer.entities.values
    if (entityList == null || entityList.length < 1) {
      return
    }
    for (let i = 0; i < entityList.length; i++) {
      let entity = entityList[i]
      if (entity.layerId == layerId && entity.objId == objId) {
        window.viewer.entities.remove(entity)
        i--
      }
    }
  }

  /**
   * 清空指定图层的所有实体
   * @param {string} layerId - 图层ID
   */
  const clearEntityLayer = (layerId) => {
    let entityList = window.viewer.entities.values
    if (entityList == null || entityList.length < 1) {
      return
    }
    for (let i = 0; i < entityList.length; i++) {
      let entity = entityList[i]
      if (entity.layerId == layerId) {
        window.viewer.entities.remove(entity)
        i--
      }
    }
  }

  /**
   * 显示连线
   * @param {string} objId - 对象ID
   * @param {Array} positions - 位置数组
   * @param {string} layerId - 图层ID
   * @param {string} color - 颜色
   * @returns {Object} 实体对象
   */
  const showPolyline = (objId, positions, layerId, color = '#00f') => {
    let material = new Cesium.PolylineGlowMaterialProperty({
      glowPower: 0.25,
      color: Cesium.Color.fromCssColorString(color).withAlpha(0.9)
    })
    
    let bData = {
      layerId: layerId,
      objId: objId,
      shapeType: "Polyline",
      polyline: {
        positions: positions,
        clampToGround: true,
        width: 8,
        material: material
      }
    }
    
    const entity = window.viewer.entities.add(bData)
    return entity
  }

  return {
    // 响应式数据
    editName,
    uavLinesInfoList,
    modeOption,
    modeNameOption,
    gimbalModeOptions,
    flightPathModeOptions,
    headingModeOptions,
    actionOptions,
    
    // 计算属性
    currentMode,
    
    // 方法
    duplicate_check,
    reName,
    backUavTask,
    clear,
    updateUGConnect,
    clearLayersEntity,
    clearEntityLayer,
    showPolyline
  }
}
